package com.onlyxiahui.common.action.description.handler.impl.method;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.onlyxiahui.common.action.description.DocumentContext;
import com.onlyxiahui.common.action.description.bean.MethodData;
import com.onlyxiahui.common.action.description.bean.ModuleData;
import com.onlyxiahui.common.action.description.bean.ParameterData;
import com.onlyxiahui.common.action.description.enums.annotation.MethodRequest;
import com.onlyxiahui.common.action.description.enums.type.ActionType;
import com.onlyxiahui.common.action.description.handler.impl.BaseMethodHandler;
import com.onlyxiahui.common.action.description.util.ActionAnnotationUtil;

/**
 * Description <br>
 * Date 2020-01-07 16:37:50<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class RequestMappingMethodHandler extends BaseMethodHandler {

	@Override
	public boolean support(DocumentContext context, ModuleData moduleData, Method method) {
		Annotation[] as = method.getAnnotations();
		boolean has = ActionAnnotationUtil.hasAnnotation(MethodRequest.RequestMapping.getAnnotation(), as);
		return has;
	}

	@Override
	public MethodData handle(DocumentContext context, ModuleData moduleData, Method method) {

		Annotation[] mas = method.getAnnotations();
		Object value = ActionAnnotationUtil.getValue(MethodRequest.RequestMapping.getAnnotation(), "value", mas);
		Object path = ActionAnnotationUtil.getValue(MethodRequest.RequestMapping.getAnnotation(), "path", mas);

		List<String> paths = new ArrayList<>();
		if (value instanceof String) {
			paths.add(value.toString());
		}
		if (value instanceof String[]) {
			String[] values = (String[]) value;
			if (null != values && values.length > 0) {
				for (String p : values) {
					paths.add(p);
				}
			}
		}

		if (path instanceof String) {
			paths.add(path.toString());
		}
		if (path instanceof String[]) {
			String[] values = (String[]) path;
			if (null != values && values.length > 0) {
				for (String p : values) {
					paths.add(p);
				}
			}
		}

		MethodData md = this.create(context, moduleData, method, paths, true);

		Object methodType = ActionAnnotationUtil.getValue(MethodRequest.RequestMapping.getAnnotation(), "method", mas);
		if (methodType instanceof Object[]) {
			Object[] vs = (Object[]) methodType;
			for (Object v : vs) {
				String key = v.toString().toLowerCase();
				String type = ActionType.getValueByType(key);
				if (null != type) {
					md.addMethodType(type);
				} else {
					md.addMethodType(key);
				}
			}
		}

		List<ParameterData> list = getMethodParameters(context, moduleData, md, method);
		List<ParameterData> parameters = handleRootMethodParameters(list);
		md.setParameters(parameters);
		return md;
	}
}
